const api_map = require("../../api.config.json");
const version = require("../../package.json").version;
console.log("版本号:", version);

let API_ORIGIN = /-dev/.test(location.host) ? api_map.development : api_map.production;
// 本地调试
if (location.host[0] > 0 || location.host == "localhost") {
  API_ORIGIN = api_map.development;
}
if (API_PROXY) {
  API_ORIGIN = api_map.test;
}

export const formatUrl = {
  _list: null,
  init() {
    if (this._list) return this._list;
    const str = location.search.slice(1);
    if (!str) return (this._list = []);
    const result = str.split("&").map((item) => {
      return item.split("=").map((v) => decodeURI(v));
    });
    return (this._list = result);
  },
  getQuery(name) {
    this.init();
    const queryItem = this._list.find((item) => {
      return item[0] == name;
    });
    const result = (queryItem && queryItem[1]) || "";
    return result;
  },
};

export function getActiveStr(str = "", total = 8) {
  let realLength = 0;
  str = String(str);
  let len = str.length;
  let result = "";
  if (len === 0) {
    return "";
  }
  for (let i = 0; i < len; i++) {
    if (str.charCodeAt(i) > 128) {
      realLength += 2;
    } else {
      realLength += 1;
    }
    if (realLength > total) {
      return result + "...";
    }
    result = result + str.charAt(i);
  }
  return result;
}

// 根据委托ID获取2DVR数据
export function requestAjax({ url, data, type }) {
  console.log("请求数据===>", url, data);
  return new Promise((resolve, reject) => {
    $.ajax({
      url: API_ORIGIN + url,
      dataType: "json",
      type: type || "get",
      data,
      success: function (res) {
        console.log("返回数据success <===", res);
        resolve(res);
      },
      error: function (res) {
        console.log("返回数据error <===", res);
        reject(res);
      },
    });
  });
}

export function formatHouseInfo(content) {
  content.area = content.area || "";
  content.addr = content.addr || "";
  content.resblockName = content.resblockName || "";
  content.buildType = content.buildType || "";
  content.direction = content.direction || "";
  content.buildSize = content.buildSize ? content.buildSize + "㎡" : "";
  content.totalPrice =
    content.totalPrice > 0
      ? content.delegationType == "SALES"
        ? content.totalPrice / 10000 + "万"
        : content.totalPrice + "元"
      : "";

  let room = content.room > 0 ? content.room + "室" : "";
  let hall = content.hall > 0 ? content.hall + "厅" : "";
  content.roomHall = room + hall;
  return content;
}

// 转发
export function shareVr(info) {
  $.ajax({
    url:
      API_ORIGIN +
      "/unified-user-gateway/api/v1/miniCode/genJsSDKConfig?miniName=shulangzh&url=" +
      encodeURIComponent(location.href),
    success: function (data) {
      console.log("微信配置数据：", data);

      wx.config({
        debug: false,
        appId: data.content.appId,
        timestamp: data.content.timestamp,
        nonceStr: data.content.nonceStr,
        signature: data.content.signature,
        jsApiList: ["updateAppMessageShareData", "updateTimelineShareData", "hideMenuItems"],
      });

      wx.ready(function () {
        wx.hideMenuItems({
          menuList: [
            "menuItem:share:qq",
            "menuItem:share:weiboApp",
            "menuItem:favorite",
            "menuItem:share:facebook",
            "menuItem:share:QZone",
            "menuItem:editTag",
            "menuItem:delete",
            "menuItem:copyUrl",
            "menuItem:originPage",
            "menuItem:readMode",
            "menuItem:openWithQQBrowser",
            "menuItem:openWithSafari",
            "menuItem:share:email",
            "menuItem:share:brand",
          ],
        });

        const params = {
          link: location.href,
          imgUrl: info.homeImg,
        };

        // 朋友圈
        wx.updateTimelineShareData({
          ...params,
          title: `【VR看房 ${info.area}${info.addr}】 ${info.resblockName} ${info.buildType} ${info.buildSize} ${info.totalPrice}`,
          success(res) {
            console.log("wx.updateTimelineShareData success", res);
          },
          cancel: function (res) {
            console.log("wx.updateTimelineShareData cancel", res);
          },
          fail: function (res) {
            console.log("wx.updateTimelineShareData fail", res);
          },
        });
        // 给好友
        wx.updateAppMessageShareData({
          ...params,
          title: `【VR看房 ${info.resblockName}】`,
          desc: `${info.buildSize} ${info.buildType} ${info.totalPrice}，点击链接查看价格与装修`,
          success(res) {
            console.log("wx.updateAppMessageShareData success", res);
          },
          cancel: function (res) {
            console.log("wx.updateAppMessageShareData cancel", res);
          },
          fail: function (res) {
            console.log("wx.updateAppMessageShareData fail", res);
          },
        });
      });
    },
  });
}

export function loadAddScript(src) {
  return new Promise((resolve, reject) => {
    let dom = document.createElement("script");
    dom.src = src;

    dom.onload = function () {
      resolve(dom);
    };

    document.body.appendChild(dom);
  });
}

//  添加调试面板
export function initDevelop() {
  // 正式服地址 && 没有debug
  if (location.host.indexOf("-dev") === -1 && !formatUrl.getQuery("debug")) {
    return Promise.resolve();
  }

  return loadAddScript("https://cdn.bootcss.com/vConsole/3.3.0/vconsole.min.js").then(() => {
    new window.VConsole();
    console.log("版本号:", version);
  });
}
